<?php
declare (strict_types=1);

namespace app\middleware;

use app\common\Jwt;
use app\system\service\UserService;
use app\traits\ApiResponseTrait;
use think\exception\ValidateException;
use think\facade\Cache;
use think\helper\Arr;
use think\Response;

class SystemAuth
{
    use ApiResponseTrait;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {
            validate([
                'authorization'  => 'require',
                'device-type'   => 'require|in:1,2',
            ])->message([
                'authorization.require' => 'authorization必须',
                'device-type.require'     => 'device-type必须',
                'device-type.in'     => 'device-typeh合法值为：[1,2]',
            ])->check($request->header());
        } catch (ValidateException $e) {
            // 验证失败
            return $this->error($e->getMessage());
        }
        if (!$token = getHeaderToken($request->header())) {
            return $this->error('缺失登录凭证');
        }
        [$isOk, $result] = Jwt::parseUserInfo($token, 'system');
        if (!$isOk) {
            return $this->error($result);
        }
        if ($result['expire'] < time()) {
            return $this->error('登录状态已经过期');
        }
        //设置用户信息
        $request->user = Arr::get($result, 'user');
        //黑名单中的记录
        if (Cache::get(UserService::generateBlackToken($token))) {
            return $this->error('登录状态已经注销');
        }
        return $next($request);
    }
}
